import 'package:flutter/material.dart';
import 'package:orginone/components/XScaffold/XScaffold.dart';
import 'package:orginone/routers/pages.dart';
import 'package:webview_flutter/webview_flutter.dart' hide WebViewController;
import 'dart:convert';
import 'package:orginone/components/Tip/ToastUtils.dart';
import 'package:orginone/main.dart';
import 'package:orginone/utils/log/log_util.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter/webview_flutter.dart' as wb;

class BrowerWidget extends StatefulWidget {
  const BrowerWidget({super.key});

  @override
  State<BrowerWidget> createState() => _BrowerState();
}

class _BrowerState extends State<BrowerWidget> {
  var title = '';

  late String url;

  late wb.WebViewController webViewController;

  @override
  void initState() {
    url = RoutePages.getPageParams['url'];

    title = "努力加载中......";
    webViewController = wb.WebViewController();
    webViewController
        .loadRequest(Uri.parse(url), headers: {'token': kernel.accessToken});
    print('>>>>>>>>>>>>>>>>>$url');
    // _startService();
    webViewController.setOnConsoleMessage((message) {
      XLogUtil.dd("web console ${message.message}");
    });
    webViewController.addJavaScriptChannel('FlutterChannel',
        onMessageReceived: onMessageReceived);
    webViewController.setJavaScriptMode(JavaScriptMode.unrestricted);
    // "alert('123');sessionStorage.setItem('accessToken', '${kernel.accessToken}');"
    webViewController.setBackgroundColor(Colors.white);
    webViewController.setNavigationDelegate(
      NavigationDelegate(
        onProgress: (int progress) {
          if (progress == 100) {
            XLogUtil.dd('>>>>>:$progress');
            webViewController.getTitle().then((value) {
              title = value ?? "";
              if (mounted) {
                setState(() {});
              }
            });
            // } else if (progress == 80) {
            webViewController.runJavaScript("""
              (function() {
                if (window.sessionStorage) {
                  window.sessionStorage.setItem("accessToken", "${kernel.accessToken}");
                  if(window.orgCtrl) {
                    console.log('>>>>>>>>window.orgCtrl');
                    window.orgCtrl.provider.init();
                  }
                }
                // 在这里注入一些JavaScript代码来初始化flutterWebView对象
                // 这个代码通常由Flutter端通过evaluateJavascript方法注入
                // window.postMessage = new Object();
                window.postMessage = function(message) {
                  // 使用自定义的postMessage方法发送消息到Flutter
                  // for(var name in window.FlutterChannel) {
                  //   console.log(name)
                  //   if(name=='flutterWebViewPostMessage') {
                  //     console.log('>>>>>>>>'+name)
                  //     break;
                  //   }
                  // }
                  window.FlutterChannel.postMessage(message);
                };
              })();
            """).then((result) {});
          }
        },
        onPageStarted: (String url) {
          XLogUtil.dd('>>>>>started:$url');
          // LoadingDialog.showLoading(context);
        },
        onPageFinished: (String url) {
          XLogUtil.dd('>>>>>finished:$url');
          // LoadingDialog.dismiss(context);
        },
        onWebResourceError: (WebResourceError error) {
          // LogUtil.dd('>>>>>error:${error.description}');
        },
      ),
    );
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return XScaffold(
      titleWidget: Text(
        title,
        style: const TextStyle(color: Colors.black),
      ),
      body: WebViewWidget(
        controller: webViewController,
      ),
    );
  }

  void onMessageReceived(JavaScriptMessage message) {
    XLogUtil.dd('JavaScript executed:${jsonEncode(message.message)}');
    switch (message.message) {
      case "saveSuccess":
        ToastUtils.showMsg(msg: "提交成功");
        RoutePages.back(context);
        break;
      default:
        break;
    }
  }

// _startService() async {
//   server = Jaguar(address: "127.0.0.1", port: 6888);
//   server.addRoute(serveFlutterAssets(path: "web/"));
//   await server.serve(logRequests: true);
// }

// @override
// void onClose() {
//   super.onClose();
//   server.close();
// }
}
